class Message < ActiveRecord::Base
  validates_presence_of :subject, :body, :sender_id
  validates_presence_of :receiver_ids, :unless => :reply?
  
  belongs_to :sender, :class_name => 'User', :foreign_key => 'sender_id'
  belongs_to :thread, :class_name => 'Message', :foreign_key => 'thread_id'
  has_many :messages, :class_name => 'Message', :foreign_key => 'thread_id'
  has_many :box_items
  
  def after_create
    self.thread_id ||= self.id
    self.send(:create_or_update_without_callbacks)
    deliver
  end
  
  def purge
    if self.box_items.empty?
      self.destroy
    end
  end

  def receivers
    users = self.participants
    users.delete sender
    users
  end
  
  def participants # thread
    users = self.receiver_ids.split(' ').collect {|receiver_id| User.find_by_login receiver_id} 
    users << self.sender
  end
  
  private
  def reply?
    thread_id
  end
  
  def deliver
    OutboxItem.create :user => self.sender, :message => self, :thread_id => self.thread_id
    self.thread.participants.each do |receiver|
      InboxItem.create :user => receiver, :message => self, :thread_id => self.thread_id unless receiver == self.sender
    end
  end
end
